package com.pb.infra.oth.service;

import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.util.UserInfo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 基础服务
 * @author 金洋
 * @date 2021/11/25
 */
@Slf4j
public class BaseService {

    /**
     * 超级管理员角色
     */
    /*@Value("${role.superMgr}")
    protected String superMgrRole;*/

    /**
     * 令牌配置信息
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * REDIS模板
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取当前Token
     * @return String Token
     */
    protected String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        return request.getHeader(jwtTokenConfig.getHeader());
    }

    /**
     * 获取当前登录用户ID
     * @return String 当前登录用户ID
     */
    protected String getCurrentUserId() {
        String token = this.getToken();
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        return (String)claims.get("sub");
    }

    /**
     * 获取当前用户信息
     * @return UserInfo 登录用户信息
     */
    protected UserInfo getCurrentUserInfo() {
        return (UserInfo)redisTemplate.opsForValue().get(this.getToken());
    }

}
